package demo2;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * 使用NIO完成网络通信的三个核心
 *
 * 一：通道，主要负责连接
 * 二：缓冲区 负责数据的存取
 * 三：选择器 是SelectableChannel的多路复用器，用于监控SelectableChannel的一些状况
 */
public class TestBlockingIO2 {

    @Test
    public void client() throws IOException {
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1",8080));

        ByteBuffer buffer = ByteBuffer.allocate(1024);

        FileChannel fileChannel = FileChannel.open(Paths.get("D:\\1\\2.jpg"), StandardOpenOption.READ);
        while (fileChannel.read(buffer)!=-1){
            buffer.flip();
            socketChannel.write(buffer);
            buffer.clear();
        }

        /**
         * 接收服务端的反馈
         */
        int len=0;
        while ((len = socketChannel.read(buffer))!=-1){
            buffer.flip();
            System.out.println(new String(buffer.array(),0,len));
            buffer.clear();
        }
        fileChannel.close();
        socketChannel.close();
    }
    @Test
    public void server() throws IOException {
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        serverSocketChannel.bind(new InetSocketAddress(8080));

        SocketChannel accept = serverSocketChannel.accept();

        FileChannel fileChannel = FileChannel.open(Paths.get("D:\\1\\1.jpg"), StandardOpenOption.CREATE, StandardOpenOption.WRITE);
        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);
        while (accept.read(byteBuffer)!=-1){
            byteBuffer.flip();
            fileChannel.write(byteBuffer);
            byteBuffer.clear();
        }

        /**
         * 发送反馈给服务端
         */
        byteBuffer.put("服务端发给客户端的反馈信息".getBytes());
        byteBuffer.flip();
        accept.write(byteBuffer);

        accept.close();
        fileChannel.close();
        serverSocketChannel.close();

    }
}
